﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows.Forms;

namespace JUtil.CodeGenerator
{
    public partial class CodeGeneLoader : Form
    {
        public bool isTesting
        {
            get
            {
                return !JUtil.Path.Directory.Application.Contains("Program Files");
            }
        }

        private string pluginPath
        {
            get
            {
                if (isTesting)
                {
                    return @"E:\GoogleProjectHosting\jelly-util-codegen\CodeGeneLoader\Plugin";
                }
                else
                {
                    return JUtil.Path.File.GetAbsolutePath(JUtil.Path.Directory.Application, "Plugin");
                }
            }
        }

        public CodeGeneLoader()
        {
            InitializeComponent();

            LoadPlugins(pluginPath);
        }

        private void LoadPlugins(string folderPath)
        {
            List<Type> tForms = GetForms(folderPath);

            foreach (Type t in tForms)
            {
                Button btn = CreateButton(t);

                pluginContainer.Controls.Add(btn);
            }
        }

        private List<Type> GetForms(string folderPath)
        {
            List<Type> retVal = new List<Type>();

            try
            {
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(folderPath);

                // 取得所有dll
                foreach (System.IO.FileInfo f in dir.GetFiles("*.dll"))
                {
                    string assemblyPath = JUtil.Path.File.GetAbsolutePath(f.DirectoryName, f.Name);

                    List<Type> tForms = GetForm(assemblyPath);
                    if (tForms.Count != 0)
                        retVal.AddRange(tForms);
                }
            }
            catch (Exception ex)
            {
            	Log.ReportError(ex);
            }

            return retVal;
        }

        private List<Type> GetForm(string assemblyPath)
        {
            List<Type> tForms = new List<Type>();

            Assembly assem = Assembly.LoadFile(assemblyPath);

            foreach (Type t in assem.GetTypes())
            {
                if (typeof(Form).IsAssignableFrom(t))
                    tForms.Add(t);
            }

            return tForms;
        }

        private Button CreateButton(Type t)
        {
            Button btn = new Button();

            btn.Text = t.Name;
            btn.Tag = t;
            btn.Click += new EventHandler(btn_Click);

            return btn;
        }

        void btn_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            Type t = (Type)btn.Tag;
            Form f = (Form) Activator.CreateInstance(t);
            f.ShowDialog();
        }
    }
}
